import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jetour_line/aha_jetour_line.dart';
import 'package:jetour_line/base_widget/base_image.dart';
import 'package:jetour_line/base_widget/base_scaffold.dart';
import 'package:jetour_line/map/base_map_widget.dart';
import 'package:jetour_line/models/jetour_line_detail.dart';
import 'package:jetour_line/my_colors.dart';
import 'package:jetour_line/network/jetour_http.dart';
import 'package:jetour_line/pages/creatTravel/creat_travel_list_widget.dart';
import 'package:jetour_line/pages/creatTravel/search_page.dart';
import 'package:jetour_line/utils/aha_utils.dart';
import 'package:jetour_line/utils/extension_int.dart';
import 'package:jetour_line/utils/page_push_utils.dart';
import '../../network/aha_http.dart';
import 'end_travel_page.dart';
typedef _EndCallBack = void Function(String img,String caption ,bool hasVideo);
class CreatTravelScreen extends StatefulWidget {
  var id;
  _EndCallBack? endCallBack;
  CreatTravelScreen({Key? key,this.id,this.endCallBack}) : super(key: key);
  @override
  State<CreatTravelScreen> createState() => _CreatTravelScreenState();
}
class _CreatTravelScreenState extends State<CreatTravelScreen> {
  int? lineId ;
  int day = 1;
  JetourDetailModel? detailModel;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.id != null){
      lineId = widget.id;
      getDetail();
    }
  }

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
        backgroundColor: MyColors.white,
        title: "创建行程",
        body: Column(
          children: [
            const Expanded(
              flex: 3,
              child: BaseMapWidget( creationParams: 1,),
            ),
            CreatTravelListWidget(detailModel: detailModel,lineId: lineId,callBack: (int selDay){
              day = selDay+1;
            },delcallBack: (int groupIndex,int childIndex){
              addMarkers();
            },),
            bottomWidget()
          ],
        ));
  }
  Widget bottomWidget(){
    return Container(
      padding: EdgeInsets.all(20.px),
      width: double.infinity,
      height: 120.px,
      child: Row(children: [
        Expanded(
          child: GestureDetector(
            onTap: (){
              int i = 0;
              if(detailModel == null || detailModel!.nodeList.isEmpty){
                AhaUtils.showTxt("请先添加地点");
                return;
              }
              PagePushUtils.push(context, EndTravelScreen(id: lineId!,detailModel: detailModel,endCallBack: widget.endCallBack,)).then((value) {
                if(value != null){
                  Navigator.pop(context);
                }
              });
            },
            child: Container(
              height: 80.px,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(40.px)),
                  color: Colors.transparent,
                  border: Border.all(width: 1.px,color: MyColors.color666666)
              ),
              child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                BaseImage(image: 'lsgj_btn_end',width: 40.px,height: 40.px),
                SizedBox(width: 8.px,),
                Text('结束行程',style: TextStyle(fontSize: 30.px,color: MyColors.color666666),),
              ],),
            ),
          ),
        ),
        SizedBox(width: 20.px,),
        Expanded(child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(40.px)),
          child: GestureDetector(
            onTap: (){
              PagePushUtils.push(context, const SearchScreen()).then((value) {
                Map<String ,dynamic> map = value as  Map<String ,dynamic> ;
                addNode(map);
              });
            },
            child: Container(
              height: 80.px,
              color: MyColors.color00A198,
              child:  Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                BaseImage(image: 'lsgj_btn_search',width: 40.px,height: 40.px),
                SizedBox(width: 8.px,),
                Text('添加地点',style: TextStyle(fontSize: 30.px,color: MyColors.white),),
              ],),
            ),
          ),
        ))
      ],),
    );
  }

  void  getDetail(){
    Map<String ,dynamic> map = Map();
    map['id'] = lineId;
    JetourHttp().get(JetourRouter.GuideToolDetail, params: map).then((value) {
      print('getDetailgetDetail$value');
      detailModel = JetourDetailModel.fromJson(value);

      addMarkers();
      setState(() {
      });
    });
  }

  Future<void> addNode(Map<String ,dynamic> map) async {
    if(lineId == null){
      var value = await JetourHttp().get(JetourRouter.GuideToolInit,);
      lineId = value['id'];
      detailModel = JetourDetailModel(caption: '',description: '',images: [],nodeList: [],videos: [],tags: [],cate: 0);
    }

    int type = map['type'];
    map['id'] = lineId;
    map['day'] = day;
    if (type == 1 || type == 2) {
      JetourHttp().post(JetourRouter.GuideToolAddNode, data: map).then((value) {
        getDetail();
      });
    } else {
      JetourHttp().post(JetourRouter.GuideToolAddNodeByContent, data: map).then((value) {
        getDetail();
      });
    }
  }
  ///添加地图marker
  void addMarkers(){
    List nodes = [];
    int index = 1;
    for(int i = 0;i<detailModel!.nodeList.length;i++){
      for(int j = 0;j<detailModel!.nodeList[i].node.length;j++){
        Node node = detailModel!.nodeList[i].node[j] ;
        Map<String,dynamic> map = {};
        map['nodeId'] = node.nodeId;
        map['index'] = index++;
        map['groupIndex'] = i;
        map['childIndex'] = j;
        map['caption'] = node.caption;
        map['lat'] = node.lat;
        map['lng'] = node.lng;
        map['type'] = 'commonDetail';
        nodes.add(map);
      }
    }
    print('detailModel.toString()${nodes.length}');
    MapUtils.addMarkers(nodes);
  }
}
